package com.jinmei.dao.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.jinmei.dao.WorkScheduleDao;
import com.jinmei.model.WorkSchedule;

public class WorkScheduleDaoImpl extends HibernateDaoSupport implements
		WorkScheduleDao {

	@Override
	public List<WorkSchedule> findAllWorkSchedules() throws DataAccessException {
		DetachedCriteria criteria = DetachedCriteria
				.forClass(WorkSchedule.class);
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public List<WorkSchedule> findWorkSchedulesByDate(String startDate,
			String endDate) throws DataAccessException, ParseException {
		
		DetachedCriteria criteria = DetachedCriteria
				.forClass(WorkSchedule.class);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date startD = sdf.parse(startDate);
		Date endD = sdf.parse(endDate);
		criteria.add(Restrictions.between("workDate", startD, endD));

		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public List<WorkSchedule> findWorkSchedulesByDateAndType(
			String workingDate, String workingType) throws DataAccessException,
			ParseException {

		DetachedCriteria criteria = DetachedCriteria
				.forClass(WorkSchedule.class);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(workingDate);

		criteria.add(Restrictions.eq("workDate", date));
		criteria.add(Restrictions.eq("workingType", new Integer(workingType)));

		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public List<WorkSchedule> findWorkSchedulesByDate(Date workDate)
			throws DataAccessException {
		DetachedCriteria criteria = DetachedCriteria
				.forClass(WorkSchedule.class);

		criteria.add(Restrictions.eq("workDate", workDate));
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public void saveOrUpdate(List<WorkSchedule> entities) {
		if (entities == null) return;
		for (WorkSchedule entity : entities) {
			this.getHibernateTemplate().saveOrUpdate(entity);
		}
	}

	@Override
	public void delete(List<WorkSchedule> entities) {
		if (entities == null) return;
		for (WorkSchedule entity : entities) {
			this.getHibernateTemplate().delete(entity);
		}
	}

}
